package com.liusu.common.utils.sm;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import lombok.extern.slf4j.Slf4j;

/**
 * 前端加密请求
 * sm2加密
 * 后端解密后加密返回值
 */
@Slf4j
public class Sm2Utils {

//     密钥生成工具：    https://www.btool.cn/sm2-key-generator


    //后台公私钥
    private final static String BACK_PRIVATE_KEY = "f33d0b3b1bd9d3298d11c4858db87eaeabfd774556803430740669b2f536bbe3";
    private final static String BACK_PUBLIC_KEY = "035c80a9b0588f3852f57e9b61d2b04077ee6dc11df09d2bbcc05fc4455b4d2167";

    //前端公钥
    private final static String FRONT_PUBLIC_KEY = "02278dd66612c74286e63c241ad9996ba64e0d86d07417ec100f5bc79bc30d7694";
    private final static String FRONT_PRIVATE_KEY = "5e834634057d372a81ec38997db9051d4764d2fc0a90506eff98fee667764c69";

    private final static SM2 SM_2 = SmUtil.sm2(BACK_PRIVATE_KEY, FRONT_PUBLIC_KEY);

    /**
     * 公钥加密
     *
     * @param cipherTxt
     * @return
     */
    public static String encrypt(String cipherTxt) {
        return ObjectUtil.isEmpty(cipherTxt) ? cipherTxt : SM_2.encryptHex(cipherTxt, KeyType.PublicKey);
    }

    /**
     * 私钥解密
     *
     * @param plainTxt
     * @return
     */
    public static String decrypt(String plainTxt) {
        return ObjectUtil.isEmpty(plainTxt) ? plainTxt : SM_2.decryptStr(plainTxt, KeyType.PrivateKey);
    }

    public static String removeQuotes(String str) {
        if (str == null || str.length() < 2) {
            return str;
        }
        if (str.charAt(0) == '\"' && str.charAt(str.length() - 1) == '\"') {
            return str.substring(1, str.length() - 1);
        }
        return str;
    }

}
